﻿using Abp.Application.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using Abp.UI;
using Microsoft.AspNetCore.Identity;
using SOEI.Solution.Authorization.Users;
using SOEI.Solution.Helper;
using SOEI.Solution.MultiTenancy;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SOEI.Solution
{
    /// <summary>
    /// Derive your application services from this class.
    /// </summary>
    public abstract class SolutionAppServiceBase : ApplicationService
    {
        public TenantManager TenantManager { get; set; }
        public UserManager UserManager { get; set; }

        protected SolutionAppServiceBase()
        {
            
            LocalizationSourceName = SolutionConsts.LocalizationSourceName;

            HttpContext.Current.Items[KeyNames.CurrentUserFunc] = (Func<User>)(() =>
            {
                return GetCurrentUserAsync().Result;
            });
        }

        protected virtual async Task<User> GetCurrentUserAsync()
        {
            var user = await UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
            if (user == null)
            {
                throw new Exception("There is no current user!");
            }

            return user;
        }

        protected virtual Task<Tenant> GetCurrentTenantAsync()
        {
            return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
        }

        protected virtual void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }



        #region -------------------------------------------------用户自定义------------------------------------------------

        /// <summary>
        /// 获取并且检查机构人员表
        /// </summary>
        /// <returns>当前登录的用户</returns>
        protected async virtual Task<User> GetPersonChecker()
        {
            //1. 获取当前登录的用户信息
            var userEntity = await this.GetCurrentUserAsync();
            //2. 判断当前登录 是否经济机构用户
            if (string.IsNullOrEmpty(userEntity.OriginalNumber))
            {
                throw new UserFriendlyException("当前登录用户不是经济机构成员！");
            }
            //HttpContext.Current.Items[KeyNames.CurrentUser] = userEntity;

            return userEntity;
        }

        /// <summary>
        /// 获取机构的电子签章编号，Q + JGBH
        /// </summary>
        /// <param name="JGBH"></param>
        /// <returns></returns>
        protected string GetOrganiSignCode(string JGBH) {
            return string.Format("Q{0}", JGBH);
        }

        /// <summary>
        /// 当前用户
        /// </summary>
        public virtual User CurrentUser
        {
            get
            {
                var vUser = HttpContext.Current.Items[KeyNames.CurrentUser];

                if (vUser == null)
                {
                    vUser = (HttpContext.Current.Items[KeyNames.CurrentUserFunc] as Func<User>)();

                    HttpContext.Current.Items[KeyNames.CurrentUser] = vUser;
                }

                return vUser as User;
            }
        }

        /// <summary>
        /// 隐私信息特殊处理
        /// 加密规则参考支付宝开放平台文档：https://opendocs.alipay.com/open/common/105912
        /// 敏感信息类型 展示规范
        /// 身份证 显示前 1 位 + *(实际位数) + 后 1 位，如： 3****************3
        /// 银行卡 显示前 6 位 + *(实际位数) + 后 4 位，如：622575******1496
        /// 手机号 显示前 3 位 + **** + 后 2 位，如：137******50
        /// </summary>
        /// <param name="value">待加密的字符串</param>
        /// <param name="startLen">开始处预保留字符串长度</param>
        /// <param name="endLen">末尾处预保留字符串长度</param>
        /// <returns></returns>
        protected static string ReplaceWithSpecialChar(string value, int startLen, int endLen)
        {
            try
            {
                int lenth = value.Length - startLen - endLen;

                string replaceStr = value.Substring(startLen, lenth);

                string specialStr = string.Empty;

                for (int i = 0; i < replaceStr.Length; i++)
                {
                    specialStr += "*";
                }

                value = value.Replace(replaceStr, specialStr);
            }
            catch (Exception)
            {
                throw;
            }

            return value;
        }



        ///// <summary>
        ///// 校验手机号码的合法性
        ///// </summary>
        ///// <param name="phone"></param>
        ///// <returns></returns>
        //public static bool CheckPhone(string phone)
        //{
        //    phone = phone.Trim();    //    去除手机号的前后空格
        //    int phoneLength = phone.Length;    //    获取手机号的长度
        //    bool phoneCheck = Regex.IsMatch(phone, @"^[1]+[3-8]+\d{9}");
        //    bool phoneCheck2 = Regex.IsMatch(phone, @"^[1]+[9][1,8,9]+\d{8}");   //针对19开头
        //    if (!phoneCheck && !phoneCheck2 || phoneLength != 11)
        //    {
        //        throw new UserFriendlyException("手机号码不合法，请准确填写11位手机号码并准确核对！");  //    手机号不合法
        //    }
        //    return true;    //    手机号合法
        //}

        ///// <summary>
        ///// 校验中国公民18位身份证号合法性
        ///// </summary>
        ///// <param name="idNumber"></param>
        ///// <returns></returns>
        //public bool CheckIDCard18(string idNumber)
        //{
        //    long n = 0;
        //    if (long.TryParse(idNumber.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
        //    {
        //        return false;//数字验证  
        //    }
        //    string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
        //    if (address.IndexOf(idNumber.Remove(2)) == -1)
        //    {
        //        return false;//省份验证  
        //    }
        //    string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
        //    DateTime time = new DateTime();
        //    if (DateTime.TryParse(birth, out time) == false)
        //    {
        //        return false;//生日验证  
        //    }
        //    string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');  //验证码取值
        //    string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');  //前17位数字本体码所对应的加权因子
        //    char[] Ai = idNumber.Remove(17).ToCharArray();
        //    int sum = 0;
        //    for (int i = 0; i < 17; i++)
        //    {
        //        sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
        //    }
        //    var y = 0;
        //    Math.DivRem(sum, 11, out y);
        //    Console.WriteLine("Y的理论值: " + y);
        //    if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
        //    {
        //        //return false;//校验码验证  
        //        throw new UserFriendlyException("身份证号填写不规范，请保证身份证号18位并核对准确！");  
        //    }
        //    return true;//符合GB11643-1999标准  
        //}
        #endregion
    }
}
